package com.echo.config;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Thymeleaf配置类，用于初始化Thymeleaf模板引擎
 */
@WebListener
public class ThymeleafConfig implements ServletContextListener {
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 获取ServletContext
        ServletContext servletContext = sce.getServletContext();
        
        // 创建模板解析器
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setPrefix("/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);
        
        // 创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        
        // 将模板引擎存储到ServletContext中，供其他组件使用
        servletContext.setAttribute("thymeleafTemplateEngine", templateEngine);
        
        System.out.println("Thymeleaf模板引擎已成功初始化");
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 清理资源
    }
}